package com.sixmac.controller.api;

import com.sixmac.controller.common.CommonController;
import com.sixmac.core.Constant;
import com.sixmac.core.ErrorCode;
import com.sixmac.core.bean.Result;
import com.sixmac.entity.AppUser;
import com.sixmac.entity.Message;
import com.sixmac.entity.vo.CodeVo;
import com.sixmac.service.MessageService;
import com.sixmac.service.AppUserService;
import com.sixmac.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2016/3/4 0004.
 */
@Controller
@RequestMapping(value = "api/appUser")
public class AppUserApi extends CommonController {

    public List<CodeVo> voList = new ArrayList<CodeVo>();

    @Autowired
    private AppUserService appUserService;

    @Autowired
    private MessageService messageService;

    /**
     * @api {post} /api/users/sendCode 发送验证码
     * @apiName users.sendCode
     * @apiGroup users
     * @apiParam {String} mobile 手机号码       <必传 />
     * @apiParam {String} type 验证码类型，注册=register，忘记密码=forgetPwd       <必传 />
     */
    @RequestMapping(value = "/sendCode")
    public void sendCode(HttpServletResponse response,
                         String mobile,
                         String type) {
        if (null == mobile || null == type) {
            WebUtil.printJson(response, new Result(false).msg(ErrorCode.ERROR_CODE_0002));
            return;
        }

        AppUser appUser = appUserService.iFindOneByMobile(mobile);

        if (type.equals("register")) {
            if (null != appUser) {
                WebUtil.printJson(response, new Result(false).msg(ErrorCode.ERROR_CODE_0006));
                return;
            }
        } else {
            if (null == appUser) {
                WebUtil.printJson(response, new Result(false).msg(ErrorCode.ERROR_CODE_0015));
                return;
            }
        }

        // 生成验证码
        String code = RandomUtil.getCode();

        // 发送验证码（云片网）
        try {
            String text = "【精诚水务】您的验证码是" + code;
            JavaSmsApi.sendSms(Constant.YUNPIAN_APPKEY, text, mobile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 将生成的验证码保存到voList中
        CodeVo codeVo = new CodeVo();
        codeVo.setMobile(mobile);
        codeVo.setCode(code);
        codeVo.setType(type);
        codeVo.setCreateTime(new Date());

        voList.add(codeVo);

        // 返回验证码
        WebUtil.printApi(response, new Result(true));
    }

    /**
     * @api {post} /api/users/register 注册
     * @apiName users.register
     * @apiGroup users
     * @apiParam {String} mobile 手机号码       <必传 />
     * @apiParam {String} password 密码，MD5密文       <必传 />
     * @apiParam {String} nickname 昵称       <必传 />
     * @apiParam {Stream} head 头像（二级制流文件）       <必传 />
     * @apiSuccess {Object} userInfo 用户信息
     * @apiSuccess {Integer} userInfo.id 用户id
     * @apiSuccess {String} userInfo.mobile 手机号
     * @apiSuccess {String} userInfo.nickName 昵称
     * @apiSuccess {String} userInfo.headPath 头像
     * @apiSuccess {Integer} userInfo.score 积分
     * @apiSuccess {String} userInfo.comName 小区名称
     * @apiSuccess {String} userInfo.comArea 小区面积
     * @apiSuccess {String} userInfo.createTime 注册时间
     * @apiSuccess {Integer} userInfo.cityId 所在城市id
     */
    @RequestMapping(value = "/register")
    public void register(HttpServletResponse response,
                         String mobile,
                         String password,
                         String nickname,
                         MultipartRequest multipartRequest) {
        if (null == mobile || null == password || null == nickname) {
            WebUtil.printJson(response, new Result(false).msg(ErrorCode.ERROR_CODE_0002));
            return;
        }

        // 检测手机号是否唯一，如果不唯一，返回错误码
        if (null != appUserService.iFindOneByMobile(mobile)) {
            WebUtil.printJson(response, new Result(false).msg(ErrorCode.ERROR_CODE_0006));
            return;
        }

        // 获取头像
        MultipartFile multipartFile = multipartRequest.getFile("head");
        if (null == multipartFile) {
            WebUtil.printJson(response, new Result(false).msg(ErrorCode.ERROR_CODE_0002));
            return;
        }

        AppUser appUser = new AppUser();
        appUser.setMobile(mobile);
        appUser.setPassword(password);
        appUser.setScore(100);
        appUser.setStatus(0);
        appUser.setCreateTime(new Date());
        appUser.setHead("");

        try {
            appUser.setHead(QiNiuUploadImgUtil.upload(multipartFile));
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 注册
        appUserService.create(appUser);

        Result obj = new Result(true).data(createMap("userInfo", appUser));
        String result = JsonUtil.obj2ApiJson(obj, "city", "password", "type");
        WebUtil.printApi(response, result);
    }

    /**
     * @api {post} /api/users/login 登录
     * @apiName users.login
     * @apiGroup users
     * @apiParam {String} mobile 手机号码       <必传 />
     * @apiParam {String} password 密码，MD5密文       <必传 />
     * @apiSuccess {Object} userInfo 用户信息
     * @apiSuccess {Integer} userInfo.id 用户id
     * @apiSuccess {String} userInfo.mobile 手机号
     * @apiSuccess {String} userInfo.nickName 昵称
     * @apiSuccess {String} userInfo.headPath 头像
     * @apiSuccess {Integer} userInfo.score 积分
     * @apiSuccess {String} userInfo.comName 小区名称
     * @apiSuccess {String} userInfo.comArea 小区面积
     * @apiSuccess {String} userInfo.createTime 注册时间
     * @apiSuccess {Integer} userInfo.cityId 所在城市id
     */
    @RequestMapping(value = "/login")
    public void login(HttpServletResponse response, String mobile, String password) {
        if (null == mobile || null == password) {
            WebUtil.printJson(response, new Result(false).msg(ErrorCode.ERROR_CODE_0002));
            return;
        }

        AppUser user = appUserService.iLogin(mobile);

        if (null == user) {
            WebUtil.printApi(response, new Result(false).msg(ErrorCode.ERROR_CODE_0018));
            return;
        }

        AppUser appUser = appUserService.iLogin(mobile, password);

        if (null == appUser) {
            WebUtil.printApi(response, new Result(false).msg(ErrorCode.ERROR_CODE_0019));
            return;
        }

        // 如果用户被禁用，将不允许登录
        if (appUser.getStatus() == Constant.STATUS_NO) {
            WebUtil.printApi(response, new Result(false).msg(ErrorCode.ERROR_CODE_0013));
            return;
        }

        Result obj = new Result(true).data(createMap("userInfo", appUser));
        String result = JsonUtil.obj2ApiJson(obj, "city", "password", "type");
        WebUtil.printApi(response, result);
    }

    /**
     * @api {post} /api/users/forgetPwd 忘记密码
     * @apiName users.forgetPwd
     * @apiGroup users
     * @apiParam {String} mobile 手机号       <必传 />
     * @apiParam {String} password 新密码，MD5密文       <必传 />
     */
    @RequestMapping(value = "/forgetPwd")
    public void forgetPwd(HttpServletResponse response, String mobile, String password) {
        if (null == mobile || null == password) {
            WebUtil.printJson(response, new Result(false).msg(ErrorCode.ERROR_CODE_0002));
            return;
        }

        // 根据手机号获取用户信息，并返回该用户的信息
        AppUser appUser = appUserService.iFindOneByMobile(mobile);

        if (null == appUser) {
            WebUtil.printApi(response, new Result(false).msg(ErrorCode.ERROR_CODE_0015));
            return;
        }

        appUser.setPassword(password);

        appUserService.update(appUser);

        WebUtil.printApi(response, new Result(true));
    }

    /**
     * @api {post} /api/users/info 查询用户信息
     * @apiName users.info
     * @apiGroup users
     * @apiParam {Integer} userId 用户id       <必传 />
     * @apiParam {Integer} loginUserId 登录用户id
     * @apiSuccess {Object} userInfo 用户信息
     * @apiSuccess {Integer} userInfo.id 用户id
     * @apiSuccess {String} userInfo.mobile 手机号
     * @apiSuccess {String} userInfo.nickName 昵称
     * @apiSuccess {String} userInfo.headPath 头像
     * @apiSuccess {Integer} userInfo.score 积分
     * @apiSuccess {String} userInfo.comName 小区名称
     * @apiSuccess {String} userInfo.comArea 小区面积
     * @apiSuccess {String} userInfo.createTime 注册时间
     * @apiSuccess {Integer} userInfo.cityId 所在城市id
     * @apiSuccess {Integer} userInfo.fansNum 粉丝数
     * @apiSuccess {Integer} userInfo.attentionNUm 关注数
     * @apiSuccess {Integer} userInfo.isAttention 是否关注，0=是，1=否
     */
    @RequestMapping(value = "/info")
    public void info(HttpServletResponse response, Integer userId, Integer loginUserId) {
        if (null == userId) {
            WebUtil.printJson(response, new Result(false).msg(ErrorCode.ERROR_CODE_0002));
            return;
        }

        AppUser appUser = appUserService.getById(userId);

        if (null == appUser) {
            WebUtil.printApi(response, new Result(false).msg(ErrorCode.ERROR_CODE_0015));
            return;
        }

        Result obj = new Result(true).data(createMap("userInfo", appUser));
        String result = JsonUtil.obj2ApiJson(obj, "city", "password", "type");
        WebUtil.printApi(response, result);
    }

    /**
     * @api {post} /api/users/updateInfo 修改用户信息
     * @apiName users.updateInfo
     * @apiGroup users
     * @apiParam {Integer} userId 用户id       <必传 />
     * @apiParam {String} password 密码，MD5密文
     * @apiParam {String} nickname 昵称
     * @apiParam {Integer} cityId 所属城市id
     * @apiParam {String} comName 小区名称
     * @apiParam {String} comArea 小区面积
     */
    @RequestMapping(value = "/updateInfo")
    public void updateInfo(HttpServletResponse response,
                           Integer userId,
                           String password,
                           String nickname,
                           Integer cityId,
                           String comName,
                           String comArea) {
        if (null == userId) {
            WebUtil.printJson(response, new Result(false).msg(ErrorCode.ERROR_CODE_0002));
            return;
        }

        AppUser appUser = appUserService.getById(userId);

        if (null == appUser) {
            WebUtil.printApi(response, new Result(false).msg(ErrorCode.ERROR_CODE_0015));
            return;
        }

        if (null != password && !password.equals("")) {
            appUser.setPassword(password);
        }

        appUserService.update(appUser);

        WebUtil.printApi(response, new Result(true));
    }

    /**
     * @api {post} /api/users/messageList 系统消息列表
     * @apiName users.messageList
     * @apiGroup users
     * @apiParam {Integer} pageNum 页码       <必传 />
     * @apiParam {Integer} pageSize 每页显示条数       <必传 />
     * @apiSuccess {Object} list 系统消息列表
     * @apiSuccess {Integer} list.id 消息id
     * @apiSuccess {String} list.title 标题
     * @apiSuccess {String} list.des 简介
     * @apiSuccess {String} list.description 描述
     * @apiSuccess {String} list.createTime 创建时间
     */
    @RequestMapping(value = "/messageList")
    public void messageList(HttpServletResponse response, Integer pageNum, Integer pageSize) {
        if (null == pageNum || null == pageSize) {
            WebUtil.printJson(response, new Result(false).msg(ErrorCode.ERROR_CODE_0002));
            return;
        }
        Page<Message> page = messageService.find(pageNum, pageSize);

        Map<java.lang.String, Object> dataMap = APIFactory.fitting(page);

        Result obj = new Result(true).data(dataMap);
        String result = JsonUtil.obj2ApiJson(obj, "types");
        WebUtil.printApi(response, result);
    }

    /**
     * @api {post} /api/users/checkCodeStatus 检测验证码是否正确
     * @apiName users.checkCodeStatus
     * @apiGroup users
     * @apiParam {String} mobile 手机号       <必传 />
     * @apiParam {String} code 验证码       <必传 />
     * @apiParam {String} type 验证码类型，注册=register，忘记密码=forgetPwd       <必传 />
     */
    @RequestMapping(value = "/checkCodeStatus")
    public void checkCodeStatus(HttpServletResponse response, String mobile, String code, String type) {
        if (null == mobile || null == code || null == type) {
            WebUtil.printJson(response, new Result(false).msg(ErrorCode.ERROR_CODE_0002));
            return;
        }

        Boolean flag = checkCode(response, mobile, code, type);

        if (flag) {
            WebUtil.printApi(response, new Result(true));
        }
    }

    /**
     * 检测验证码是否正确
     *
     * @param response
     * @param mobile
     * @param code
     * @param type
     */
    public Boolean checkCode(HttpServletResponse response, String mobile, String code, String type) {
        Boolean flag = false;
        Boolean result = false;

        try {
            // 检查验证码是否正确，如果不正确，返回错误码
            CodeVo tempCodeVo = null;
            for (CodeVo codeVo : voList) {
                if (codeVo.getCode().equals(code) && codeVo.getMobile().equals(mobile)) {
                    flag = true;
                    tempCodeVo = codeVo;
                }
            }

            if (flag == false) {
                WebUtil.printApi(response, new Result(false).msg(ErrorCode.ERROR_CODE_0004));
                return result;
            } else if (!tempCodeVo.getType().equals(type)) {
                WebUtil.printApi(response, new Result(false).msg(ErrorCode.ERROR_CODE_0005));
                return result;
            } else if (DateUtils.secondCompare(tempCodeVo.getCreateTime(), 600)) {
                // 如果存在，则检测是否超时，如果超时，返回错误信息
                WebUtil.printApi(response, new Result(false).msg(ErrorCode.ERROR_CODE_0014));
                return result;
            }

            if (flag) {
                // 如果匹配到了，则移除缓存中的验证码实体信息
                Iterator iter = voList.iterator();
                CodeVo vo = null;
                while (iter.hasNext()) {
                    vo = (CodeVo) iter.next();
                    if (vo.getMobile().equals(mobile)) {
                        iter.remove();
                    }
                }
            }

            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
}
